<!--
 * @Descripttion: 
 * @version: 
 * @Author: xcb
 * @Date: 2021-03-16 09:48:46
 * @LastEditors: yangyongtao
 * @LastEditTime: 2023-12-04 10:47:36
-->
<template>
  <div style="width: 100%; height: 100%; position: relative">
    <button class="page-button" style="margin: 0px" @click="goBack">
      返回上级
    </button>

    <el-divider />

    <el-form
      ref="ruleFormRef"
      :model="planMsgForm"
      :rules="rules"
      label-width="100px"
      hide-required-asterisk
    >
      <el-form-item label="方案名称" prop="planName">
        <el-input
          v-model="planMsgForm.planName"
          placeholder="请输入方案名称"
          :readonly="!planDataMsgForm.verifyUser"
        />
      </el-form-item>
      <el-form-item label="方案备注">
        <el-input
          v-model="planMsgForm.planRemark"
          placeholder="请输入方案备注"
          :readonly="!planDataMsgForm.verifyUser"
        />
      </el-form-item>

      <el-divider />

      <el-form-item label="计算库区">
        <el-select
          style="width: 100%"
          v-model="planDataMsgForm.selectReservoir"
          :disabled="!planDataMsgForm.verifyUser"
          @change="getParamPlanList"
        >
          <el-option
            v-for="(item, i) in $store.state.reiverList"
            :key="i"
            :value="item.reservoir"
            :label="item.reservoir"
            :disabled="item.disabled"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="总参数方案">
        <el-select
          style="width: 100%"
          v-model="planDataMsgForm.selectParamPlan"
          :disabled="!planDataMsgForm.verifyUser"
        >
          <el-option
            v-for="(item, i) in paramPlanList"
            :key="i"
            :value="item.id"
            :label="item.name"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="降雨量模型">
        <el-select
          style="width: 100%"
          v-model="planDataMsgForm.selectRainModelPlan"
          :disabled="!planDataMsgForm.verifyUser"
        >
          <el-option
            v-for="(item, i) in rainModelList"
            :key="i"
            :value="item.id"
            :label="item.name"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="水沙模型">
        <el-select
          style="width: 100%"
          v-model="planDataMsgForm.selectFormulasModelPlan"
          :disabled="!planDataMsgForm.verifyUser"
        >
          <el-option
            v-for="(item, i) in formulasModelList"
            :key="i"
            :value="item.id"
            :label="item.name"
          ></el-option>
        </el-select>
      </el-form-item> -->

      <el-form-item label="时间范围">
        <el-date-picker
          v-model="planDataMsgForm.dateTime"
          type="daterange"
          value-format="YYYY-MM-DD"
          :disabled="!planDataMsgForm.verifyUser"
          :clearable="false"
          :editable="false"
          prefix-icon="none"
          style="width: 100%"
        ></el-date-picker>
      </el-form-item>
    </el-form>

    <button
      v-if="planDataMsgForm.selectReservoir != '长江中下游'"
      :class="['page-button', { 'active-page-button': activeButton === 0 }]"
      @click="pageButtonClick(0)"
    >
      初始化参数
    </button>
    <button
      :class="['page-button', { 'active-page-button': activeButton === 1 }]"
      @click="pageButtonClick(1)"
    >
      边界条件
    </button>
    <button
      :class="['page-button', { 'active-page-button': activeButton === 2 }]"
      @click="pageButtonClick(2)"
    >
      调度方案
    </button>
    <!-- <button
      :class="['page-button', { 'active-page-button': activeButton === 3 }]"
      @click="pageButtonClick(3)"
    >
      河道断面
    </button> -->
    <button
      v-if="
        planDataMsgForm.selectReservoir === '三峡库区' ||
        planDataMsgForm.selectReservoir === '长江中下游'
      "
      :class="['page-button', { 'active-page-button': activeButton === 4 }]"
      @click="pageButtonClick(4)"
    >
      泥沙参数
    </button>
    <button
      :class="['page-button', { 'active-page-button': activeButton === 5 }]"
      @click="pageButtonClick(5)"
    >
      关系图
    </button>

    <button
      v-if="planDataMsgForm.verifyUser"
      class="page-button"
      style="position: absolute; bottom: 0; left: 0"
      @click="planCalculate(ruleFormRef)"
    >
      计算
    </button>
  </div>
</template>

<script lang="ts">
import {
  ref,
  defineComponent,
  reactive,
  provide,
  inject,
  watch,
  toRefs,
  onMounted,
} from "vue";
import { useStore } from "vuex";
import { useRoute, useRouter } from "vue-router";
import { cloneDeep } from "lodash-es";
import moment, { Moment } from "moment";
import * as echarts from "echarts";

import {
  selectArgumentsInfoList,
  getSelectRainModelInfo,
  addYcPlan,
  updateYiweiYcPlan,
  saveWriteParameter,
  writeBoundary,
  getDataFlowWrittenDatabase,
  runYiWeiModel,
  reservoirLevelWrite,

  // 长江中下游
  insertScheme, // 创建方案
  writeCJWater, // 写入边界条件
  runPython,
  selectSingleWaterModelInfo, // 运行模型
} from "@/request/api";
import { ElMessage } from "element-plus";
import type { FormInstance } from "element-plus";

const rules = {
  planName: [{ required: true, message: "请输入方案名称", trigger: "blur" }],
};

export default defineComponent({
  name: "sideForm",
  props: {},
  setup: (props) => {
    const store = useStore();
    const route = useRoute();
    const router = useRouter();
    const ruleFormRef = ref<FormInstance>();

    const state = reactive({
      // 参数方案列表
      paramPlanList: [],
      // 降雨量模型列表
      rainModelList: [],
      // 水沙模型列表
      formulasModelList: [],
      // 所选分页按钮序号
      activeButton: 0,
    });

    // 展示页面
    let pageType: any = inject("pageType");

    // 方案基础信息
    const planMsgForm: any = inject("planMsgForm");

    // 方案参数信息
    const mainData: any = inject("mainData");

    // 初始化参数
    let planDataMsgForm: any = inject("planDataMsgForm");

    // 边界条件数据
    let boundaryConditionData: any = inject("boundaryConditionData");

    // 坝前水位数据
    let schemePresetData: any = inject("schemePresetData");

    watch(
      () => planDataMsgForm,
      (value, prevCount) => {
        if (
          state.activeButton === 0 &&
          value.selectReservoir === "长江中下游"
        ) {
          pageButtonClick(1);
        }
      },
      { deep: true }
    );

    onMounted(() => {
      setTimeout(() => {
        getParamPlanList();
      }, 0);
    });

    /**
     * @description: 根据所选库区获得参数方案列表和断面测次
     * @return {*}
     */
    async function getParamPlanList() {
      // 参数方案列表获取
      const argumentsRequstData: any = await selectArgumentsInfoList({
        createName: "",
        name: "",
        reservoir: planDataMsgForm.selectReservoir,
        river: store.state.reiverList.find(
          (item) => item.reservoir === planDataMsgForm.selectReservoir
        ).river,
      });

      if (argumentsRequstData.length != 0) {
        state.paramPlanList = argumentsRequstData;

        // 判断当前方案是否为编辑
        if (route.params.isEdit != "true") {
          planDataMsgForm.selectParamPlan = argumentsRequstData[0].id;
        }
      } else {
        state.paramPlanList = [];
        planDataMsgForm.selectParamPlan = "当前库区暂无参数方案";
      }

      planDataMsgForm.selectRainModelPlan = "";
      planDataMsgForm.selectFormulasModelPlan = "";

      const riverModelRequstData: any = await getSelectRainModelInfo({
        reservoir: planDataMsgForm.selectReservoir,
      });

      const formulasModelRequstData: any = await selectSingleWaterModelInfo({
        reservoir: planDataMsgForm.selectReservoir,
      });

      if (riverModelRequstData.length != 0) {
        state.rainModelList = riverModelRequstData;
        state.formulasModelList = formulasModelRequstData;

        // 判断当前方案是否为编辑
        if (route.params.isEdit != "true") {
          // planDataMsgForm.selectParamPlan = riverModelRequstData[0].id;
        }
      } else {
        state.rainModelList = [];
        state.formulasModelList = [];
        // planDataMsgForm.selectParamPlan = "当前库区暂无参数方案";
      }
    }

    /**
     * @description: 切换展示的内容
     * @param {*} val 点击的按钮序号
     * @return {*}
     */
    function pageButtonClick(val) {
      state.activeButton = val;

      switch (val) {
        case 0:
          pageType.value = "初始化参数";
          break;
        case 1:
          pageType.value = "边界条件";

          // 图表resize
          setTimeout(() => {
            try {
              const topChart = echarts.init(
                document.getElementById("top-echarts")
              );
              topChart.resize();
            } catch (error) {}

            try {
              const btmChart = echarts.init(
                document.getElementById("bottom-echarts")
              );
              btmChart.resize();
            } catch (error) {}

            try {
              const schemePresetEcharts = echarts.init(
                document.getElementById("schemePresetEcharts")
              );

              schemePresetEcharts.resize();
            } catch (error) {}
          }, 0);
          break;
        case 2:
          pageType.value = "调度方案";

          // 图表resize
          setTimeout(() => {
            try {
              const btmChart = echarts.init(
                document.getElementById("dispatchingScheme-bottom-echarts")
              );
              btmChart.resize();
            } catch (error) {}

            try {
              const schemePresetEcharts = echarts.init(
                document.getElementById("schemePresetEcharts")
              );

              schemePresetEcharts.resize();
            } catch (error) {}
          }, 0);
          break;
        case 3:
          pageType.value = "河道断面";

          // 图表resize
          setTimeout(() => {
            let mileageEcharts = echarts.init(
              document.getElementById("mileageEcharts")
            );
            let sectionCharts = echarts.init(
              document.getElementById("sectionCharts")
            );

            mileageEcharts.resize();
            sectionCharts.resize();
          }, 0);
          break;
        case 4:
          pageType.value = "泥沙参数";
          break;
        case 5:
          pageType.value = "关系图";

          // 图表resize
          setTimeout(() => {
            let visTreeEcharts = echarts.init(
              document.getElementById("visTree")
            );

            visTreeEcharts.resize();
          }, 0);
          break;
      }
    }

    /**
     * @description: 方案进行计算
     * @return {*}
     */
    function planCalculate(formEl: FormInstance | undefined) {
      if (!formEl) return;
      formEl.validate(async (valid) => {
        if (valid) {
          let planno: any = "";

          const paramPlan = state.paramPlanList.find(
            (item) => item.id === planDataMsgForm.selectParamPlan
          );

          await ElMessage("正在新建方案与写入数据中，请稍后");

          if (planDataMsgForm.selectReservoir === "长江中下游") {
            ElMessage.success("模型开始计算，稍后返回列表页面");

            if (route.params.isEdit != "true") {
              // 方案新增同时进行参数写入
              await insertScheme({
                schemeName: planMsgForm.planName, //方式名称
                remark: planMsgForm.planRemark, // 备注
                userName: "王伟", // 用户名
                argumentsid: planDataMsgForm.selectParamPlan, // 总参数方案
                gradationId:
                  "1b4cd23c503545cbae2a38873244ea01,dbae3ca9080d432682136dd70fca7e42", // 床沙级配id  包括宜昌 洞庭湖
                roughnessId: paramPlan.cl, // 糙率id 包括宜昌 洞庭湖
                particlesId: paramPlan.kms, // 颗粒级配id
                networkId: "265ee611c36545b18c0473a109d6e40d", // 河网结构id
                startCode: "1", // 热启动
                startTime: planDataMsgForm.dateTime[0],
                endTime: planDataMsgForm.dateTime[1],
                queryType: "1", // 1
              }).then((res: any) => {
                if (res.code === 200) {
                  planno = res.msg;
                }
              });
            } else {
              planno = route.params.planno;
            }

            let boundaryJson = {};

            // 循环河流对象
            for (const riverKey in boundaryConditionData) {
              // 循环河流下的数据类型对象(ll,ns,sw)
              for (const dataTypeKey in boundaryConditionData[riverKey]) {
                // 如果boundaryJson中不存在当前数据类型 则进行新增
                if (!boundaryJson.hasOwnProperty(dataTypeKey)) {
                  boundaryJson[dataTypeKey] = {};
                }
                // 将边界条件进行赋值
                boundaryJson[dataTypeKey][riverKey] =
                  boundaryConditionData[riverKey][dataTypeKey];
              }
            }

            // 写入边界条件
            await writeCJWater({
              path: planno,
              jsonObject: boundaryJson,
              fileName: "s",
            }).then((res) => {});

            // boundary文件写入数据库
            await getDataFlowWrittenDatabase({
              planno: "0a692fa99a80431ba3bb07adce80ebd6",
              planName: planMsgForm.planName,
              data: JSON.stringify(boundaryJson),
            }).then((res) => {});

            await ElMessage.success("模型开始计算，稍后返回列表页面");

            await setTimeout(() => {
              router.push({
                name: "sedimentScheme_manage",
                params: {},
              });
            }, 3000);

            // 运行一维程序
            await runPython({
              pathId: planno,
            }).then((res) => {});
          } else {
            if (route.params.isEdit != "true") {
              // 方案新增
              await addYcPlan({
                planName: planMsgForm.planName,
                remark: planMsgForm.planRemark,
                userName: "王伟",
                // import.meta.env.DEV
                //   ? "王伟"
                //   : JSON.parse(localStorage.getItem("userList")).token,
                planno: "modelTemp",
                argumentsid: paramPlan.selectParamPlan,
              }).then((res: any) => {
                if (res) {
                  planno = res.newPlanno;
                }
              });
            } else {
              planno = route.params.planno;
            }

            // 初始化参数中时间参数写入
            await updateYiweiYcPlan({
              step: mainData.timeData.step,
              xscdStep: mainData.timeData.xscdStep * 3600,
              stcdStep: mainData.timeData.stcdStep * 3600,
              offsets: mainData.timeData.offsets,
              roughness: mainData.timeData.roughness,
              planno,
              area: planDataMsgForm.selectReservoir,
            }).then((res: any) => {});

            // 参数方案写入
            await saveWriteParameter({
              // rainModelId: planDataMsgForm.selectRainModelPlan,
              // formulasModelId: planDataMsgForm.selectFormulasModelPlan,
              argumentsid: planDataMsgForm.selectParamPlan,
              area: planDataMsgForm.selectReservoir,
              river: store.state.reiverList.find(
                (item) => item.reservoir === planDataMsgForm.selectReservoir
              ).river,
              planno,
              xscdStep: mainData.timeData.xscdStep * 3600,
              stcdStep: mainData.timeData.stcdStep * 3600,
              offsets: mainData.timeData.offsets,
              roughness: mainData.timeData.roughness,
            }).then((paramRes) => {});

            let boundaryJson = {};

            // 循环河流对象
            for (const riverKey in boundaryConditionData) {
              // 循环河流下的数据类型对象(ll,ns,sw)
              for (const dataTypeKey in boundaryConditionData[riverKey]) {
                // 如果boundaryJson中不存在当前数据类型 则进行新增
                if (!boundaryJson.hasOwnProperty(dataTypeKey)) {
                  boundaryJson[dataTypeKey] = {};
                }
                // 将边界条件进行赋值
                boundaryJson[dataTypeKey][riverKey] =
                  boundaryConditionData[riverKey][dataTypeKey];
              }
            }

            // boundary文件写入文件
            await writeBoundary({
              area: planDataMsgForm.selectReservoir,
              startTime: planDataMsgForm.dateTime[0],
              endTime: planDataMsgForm.dateTime[1],
              planno,
              planName: planMsgForm.planName,
              boundaryJson: JSON.stringify(boundaryJson),
              predictDay: planDataMsgForm.predictDay,
            }).then((res) => {});

            // boundary文件写入数据库
            await getDataFlowWrittenDatabase({
              planno,
              planName: planMsgForm.planName,
              data: JSON.stringify(boundaryJson),
            }).then((res) => {});

            // 坝前水位写入数据库
            await reservoirLevelWrite({
              Data: JSON.stringify(schemePresetData),
              planno,
            }).then((res) => {});

            await ElMessage.success("模型开始计算，稍后返回列表页面");

            await setTimeout(() => {
              router.push({
                name: "sedimentScheme_manage",
                params: {},
              });
            }, 3000);

            // 运行一维程序
            await runYiWeiModel({
              planno,
            }).then((res: any) => {});
          }
        } else {
          return false;
        }
      });
    }

    /**
     * @description: 返回上一级页面
     * @return {*}
     */
    function goBack() {
      router.back();
    }

    return {
      ...toRefs(state),

      rules,
      ruleFormRef,

      // 展示分页
      pageType,

      // 方案基础信息
      planMsgForm,
      // 初始化参数
      mainData,
      // 方案参数信息
      planDataMsgForm,
      // 边界条件数据
      boundaryConditionData,

      // 根据所选库区获得参数方案列表
      getParamPlanList,

      // 切换页面
      pageButtonClick,

      // 方案计算
      planCalculate,

      // 返回上一个页面
      goBack,
    };
  },
});
</script>

<style scoped lang="less">
.page-button {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  padding: 8px 15px;
  margin: 0 0 10px 0;
  cursor: pointer;
  width: 100%;
  border-radius: 10px;
}

.active-page-button {
  color: #fff;
  background-color: #409eff;
}
</style>
